<?php
/**
 * 微信支付回調
 * author universe.h
 */
namespace Api\Controller;

use Common\Lib\Wxpay\Notify;
use Think\Controller;

class WxpayController extends Controller
{
    // 支付回調方法
    public function OrderChange()
    {
        \Think\Log::write("微信支付回调开始", '', '', './WXpaylog/Callback' . date('y_m_d') . '.log');
        $notify = new Notify();
        $notify->notifySet();
        \Think\Log::write("微信支付回调结束", '', '', './WXpaylog/Callback' . date('y_m_d') . '.log');
        //领取红包
        $this->enveReceive();
    }

    /**
     * 领取红包
     * @return bool
     */
    private function enveReceive()
    {
        $postStr  = file_get_contents("php://input");
        $postdata = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //红包信息
        $enve_model = M("Enve");
        $enve_info  = $enve_model->where(['out_trade_no' => $postdata['out_trade_no'], 'pay_status' => 'ok', 'del' => 0])->find();
        if (!$enve_info) {
            return false;
        }
        $pid = $enve_info['id'];
        //讨彩头信息
        $tct_model = M('Taocaitou');
        $tct_info  = $tct_model->where(['id' => $enve_info['tct_id']])->find();
        if (!$tct_info) {
            return false;
        }
        //余额支付领取红包
        if ($enve_info['pay_type'] != 1 || $enve_info['amount'] == 0) {
            return false;
        }
        $enveInfo   = [
            'moneyList'  => [$enve_info['amount']],
            'amount'     => $enve_info['amount'],
            'receiveNum' => 0,
            'enveNum'    => 1,
            'users'      => []
        ];
        $param      = [
            'tct_id'   => $enve_info['tct_id'],
            'quest'    => $enve_info['quest'],
            'tct_info' => $tct_info
        ];
        $rceiveData = [
            'pid' => $pid
        ];
        $ret        = $this->saveEnveReceive($param, $rceiveData, $enveInfo);
        if (!$ret) {
            return false;
        } else {
            //清除缓存
            $this->clearCacheList($tct_info['user_id']);
            $this->clearCacheList($enve_info['user_id']);
            $this->clearCacheDetail($enve_info['tct_id']);
            //增加排行榜集字数，每天每人每组每字记录一次
            $this->incRankNum($tct_info,$enve_info);

            return true;
        }
    }

    //清除列表缓存
    private function clearCacheList($userId = 0)
    {
        $cacheSendList     = 'TaocaitouController' . 'sendList';
        $cacheSendEnveList = 'TaocaitouController' . 'sendEnveList';

        S($cacheSendList . $userId, null);
        S($cacheSendEnveList . $userId, null);
    }

    //清除详情缓存
    private function clearCacheDetail($tctId = 0)
    {
        $cacheDetail    = 'TaocaitouController' . 'detail';
        $cacheDetailTwo = 'TaocaitouController' . 'detailTwo';
        S($cacheDetail . $tctId, null);
        S($cacheDetailTwo . $tctId, null);
    }

    /**
     * 领取红包
     * time 2017.9.30
     */
    private function saveEnveReceive($param = [], $post_data = [], $enveInfo = [])
    {
        $tct_id = (int)$param['tct_id'];
        $pid    = (int)$post_data['pid'];
        //讨彩头信息
        $tct_model = M('Taocaitou');
        $tct_info  = $param['tct_info'];
        if (!$tct_info) {
            return false;
        }
        $post_data['tct_id']         = $tct_id;
        $post_data['receive_answer'] = $tct_info['content'];
        //用户id
        $userId     = (int)$tct_info['user_id'];
        $user_model = M('WxUser');
        $user       = $user_model->field(['id', 'nick_name', 'head_img'])->where(['id' => $userId])->find();
        //加入用户信息
        $post_data['user_id']   = $userId;
        $post_data['nick_name'] = $user['nick_name'];
        $post_data['head_img']  = $user['head_img'];
        //红包信息
        $enve_model = M("Enve");

        //检测是否领取过红包
        $enve_receive_model = D("EnveReceive");

        $enveInfo['amount']     = number_format($enveInfo['amount'] - $enveInfo['moneyList'][0], 2);
        $enveInfo['receiveNum'] = $enveInfo['receiveNum'] + 1;
        $receive_amount         = $enveInfo['moneyList'][0];
        array_splice($enveInfo['moneyList'], 0, 1);
        $enveInfo['users'][] = $userId;

        //插入领红包选项检测
        $post_data['receive_amount'] = $receive_amount;
        $post_data                   = $enve_receive_model->create($post_data);
        if (!$post_data) {
            return false;
        };

        //开始事务
        M()->startTrans();
        //更新红包数量和金额
        $data = ['amount' => $enveInfo['amount'], 'receive_num' => $enveInfo['receiveNum'], 'update_time' => time()];
        $res  = $enve_model->where('id=' . $pid . ' and del=0')->save($data);
        if (!$res) {
            $enve_model->rollback();

            return false;
        }

        //领取表入库
        $last_id = $enve_receive_model->add($post_data);
        if (!$last_id) {
            $enve_receive_model->rollback();

            return false;
        }

        //更新用户余额
        $res_user = $user_model->where(['id' => $userId])->setInc('amount', $receive_amount); // 增加money到余额
        if (!$res_user) {
            $user_model->rollback();

            return false;
        }

        //插log
        $log_data = [
            'pay_type'   => '1',
            'amount'     => $receive_amount,
            'pay_status' => 'ok',
            'desc'       => get_log_tpl('receive_enve'),
            'source'     => __ACTION__,
            'add_time'   => time(),
            'user_id'    => $userId,
            'enve_id'    => $pid,
        ];
        $res_log  = set_money_log($log_data);
        if (!$res_log) {
            M('MoneyLog')->rollback();

            return false;
        }
        //更新讨彩头数据
        $data          = [];
        $words         = $tct_info['words'] ? explode(',', $tct_info['words']) : [];
        $words[]       = $param['quest'];
        $data['words'] = implode(',', $words);
        $content       = explode(',', $tct_info['content']);
        $status        = true;
        foreach ($content as $v) {
            if (!in_array($v, $words)) {
                $status = false;
            }
        }
        if ($status) {
            $data['status'] = 2;
        }
        $res = $tct_model->where(['id' => $tct_id])->setInc('num', 1);
        if ($res) {
            $res = $tct_model->where(['id' => $tct_id])->setInc('amount', $receive_amount);
        }
        if ($res) {
            $res = $tct_model->where(['id' => $tct_id])->save($data);
        }
        if (!$res) {
            $tct_model->rollback();

            return false;
        }
        //提交事务
        M()->commit();

        return true;
    }

    /**
     * 增加排行榜集字数，每天每人每组每字记录一次
     */
    private function incRankNum($tct_info,$enve_info)
    {
        //增加排行榜集字数，每天每人每组每字记录一次
        $content        = explode(',', $tct_info['content']);
        $index        = (string)array_search($enve_info['quest'], $content);
        $cacheKeyRank = 'cacheIncRankNum:'.$tct_info['user_id'].date('Ymd').$enve_info['user_id'].$tct_info['id'].$index;
        if(!S($cacheKeyRank)){
            $Model = M();
            $sql = "UPDATE `hb_wx_user` SET `rank_num`=rank_num+1 WHERE `id` = ".$tct_info['user_id'];
            $ret = $Model->execute($sql);
        }
        S($cacheKeyRank,1, ['expire' => 86400]);

        return true;
    }
}

